package com.rongshu.view.home.activity;

import android.Manifest;
import android.animation.Animator;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.widget.NestedScrollView;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.rongshu.R;
import com.rongshu.utils.AnimationUtil;
import com.rongshu.utils.BitmapUtils;
import com.rongshu.utils.BlurUtil;
import com.rongshu.utils.Constant;
import com.rongshu.utils.DateUtils;
import com.rongshu.utils.FileUtils;
import com.rongshu.utils.UserInfoUtils;
import com.rongshu.view.base.BaseActivity;
import com.rongshu.view.home.entity.DaySignInfo;
import com.rongshu.view.home.widget.SelectableTextView;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.utils.AppInstallUtils;
import com.utils.DensityUtil;
import com.utils.permissions.OnPermission;
import com.utils.permissions.XXPermissions;
import com.widget.loading.AnimatorListener;
import com.widget.toast.ToastUtils;

import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * created by zhengweis on 2019/8/1.
 * description：
 */
public class ShareDaySignActivity extends BaseActivity {
    @BindView(R.id.share_sign_img)
    ImageView shareSignImg;
    @BindView(R.id.sign_time)
    TextView signTime;
    @BindView(R.id.sign_content)
    SelectableTextView signContent;
    @BindView(R.id.sign_author)
    TextView signAuthor;
    @BindView(R.id.share_layout)
    NestedScrollView scrollLayout;
    @BindView(R.id.share_layout_data)
    LinearLayout shareLayout;
    @BindView(R.id.share_item_layout)
    LinearLayout shareItemLayout;
    @BindView(R.id.layout_bg)
    ImageView layoutBgf;
    @BindView(R.id.layout_white_bg)
    ImageView layoutWhiteBg;
    @BindView(R.id.iv_white_data)
    ImageView ivWhitedata;
    @BindView(R.id.iv_black_data)
    ImageView ivBlackdata;
    //日签
    private DaySignInfo.ResponseBean signInfo = null;
    //permission
    private String[] mPermissionList = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE};
    private Handler handler = new Handler();
    private boolean animationIsFinish = false;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        hintTitleBar();
    }

    @Override
    protected int initLayout() {
        return R.layout.activity_share_day_sign;
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    protected void initView() {
        scrollLayout.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    finish();
                }
                return true;
            }
        });
        Intent intent = getIntent();
        signInfo = (DaySignInfo.ResponseBean) intent.getSerializableExtra(Constant.INTENT_DATA);
        if (signInfo != null) {
            signContent.setText(signInfo.getDailyContent());
            signAuthor.setText(signInfo.getIsSystem() == Constant.DAY_SIGN_RONGSHU ? "" : UserInfoUtils.getBiName());
            String dailyDate = signInfo.getDailyDate();
            if (!TextUtils.isEmpty(dailyDate)) {
                Date date = DateUtils.parseDate(DateUtils.YYYY_MM_DD, dailyDate);
                String share_data = DateUtils.formatDate("yyyy年MM月", date);
                String week = DateUtils.formatDate("E", date);
                String day = DateUtils.formatDate("dd", date);
                signTime.setText(share_data + "/" + week);
                //img
                ivWhitedata.setImageResource(FileUtils.getResource(this, "date_white_" + day));
                ivBlackdata.setImageResource(FileUtils.getResource(this, "date_black_" + day));
            }
        }
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (!animationIsFinish && signInfo != null) {
            loadImg();
        }
        animationIsFinish = true;
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void updateViews(boolean isRefresh) {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    @OnClick({R.id.share_wechat, R.id.share_wechat_circle, R.id.share_weibo, R.id.share_qq, R.id.share_qzone})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.share_wechat:
                if (AppInstallUtils.isWeixinAvilible(this)) {
                    checkPermission(SHARE_MEDIA.WEIXIN);
                } else {
                    ToastUtils.show("\"微信\"不可用\n请检查手机是否安装\"微信\"");
                }
                break;
            case R.id.share_wechat_circle:
                if (AppInstallUtils.isWeixinAvilible(this)) {
                    checkPermission(SHARE_MEDIA.WEIXIN_CIRCLE);
                } else {
                    ToastUtils.show("\"微信\"不可用\n请检查手机是否安装\"微信\"");
                }
                break;
            case R.id.share_weibo:
                if (AppInstallUtils.isWBAvailable(this)) {
                    checkPermission(SHARE_MEDIA.SINA);
                } else {
                    ToastUtils.show("\"新浪微博\"不可用\n请检查手机是否安装\"新浪微博\"");
                    return;
                }
                break;
            case R.id.share_qq:
                if (AppInstallUtils.isQQAvailable(this)) {
                    checkPermission(SHARE_MEDIA.QQ);
                } else {
                    ToastUtils.show("\"QQ\"不可用\n请检查手机是否安装\"QQ\"");
                    return;
                }
                break;
            case R.id.share_qzone:
                if (AppInstallUtils.isQQAvailable(this)) {
                    checkPermission(SHARE_MEDIA.QZONE);
                } else {
                    ToastUtils.show("\"QQ\"不可用\n请检查手机是否安装\"QQ\"");
                    return;
                }
                break;
        }
    }

    private void checkPermission(final SHARE_MEDIA type) {
        if (!XXPermissions.isHasPermission(this, mPermissionList)) {
            XXPermissions.with(this).permission(mPermissionList).request(new OnPermission() {
                @Override
                public void hasPermission(List<String> granted, boolean isAll) {
                    toShare(type);
                }

                @Override
                public void noPermission(List<String> denied, boolean quick) {

                }
            });
        } else {
            toShare(type);
        }
    }

    public void toShare(SHARE_MEDIA type) {
        //分享
        Bitmap bitmap = BitmapUtils.loadBitmapFromView(shareLayout);
        if (bitmap == null) {
            toast("分享图片不可为空");
            return;
        }
        UMImage image = new UMImage(this, bitmap);
        new ShareAction(this)
                .setPlatform(type)//传入平台
                .withMedia(image).setCallback(new UMShareListener() {
            @Override
            public void onStart(SHARE_MEDIA share_media) {

            }

            @Override
            public void onResult(SHARE_MEDIA share_media) {
            }

            @Override
            public void onError(SHARE_MEDIA share_media, Throwable throwable) {
                ToastUtils.show(throwable.getMessage());
            }

            @Override
            public void onCancel(SHARE_MEDIA share_media) {
            }
        }).share();
    }

    private void loadImg() {
        Glide.with(this).load(signInfo.getImgUrl())
                .listener(new RequestListener<Drawable>() {
                    @Override
                    public boolean onLoadFailed(@Nullable GlideException e, Object model,
                                                Target<Drawable> target, boolean isFirstResource) {
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(Drawable resource, Object model,
                                                   Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                        BitmapDrawable bd = (BitmapDrawable) resource;
                        Bitmap bdBitmap = bd.getBitmap();
                        //背景虚化
                        Bitmap newImg = BlurUtil.doBlur(bdBitmap, 10, 10);
                        rootLayout.setBackground(new BitmapDrawable(getResources(), newImg));
                        handler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                //延迟150ms隐藏白色背景，模拟截图效果
                                layoutWhiteBg.setVisibility(View.GONE);
                                //根据比例缩放view的宽高：10:7
                                int screenHeight = DensityUtil.getScreenHeight(ShareDaySignActivity.this);
                                float currentHeight = screenHeight / 10.0f * 7.0f;
                                int shareHeigh = shareLayout.getMeasuredHeight();
                                float distance;
                                float ratio;
                                if (currentHeight > shareHeigh) {
                                    ratio = shareHeigh / currentHeight;
                                    distance = (currentHeight - shareHeigh) / 2 - getResources().getDimensionPixelOffset(R.dimen.dd_dimen_120px);
                                } else {
                                    ratio = currentHeight / shareHeigh;
                                    distance = (shareHeigh - currentHeight) / 2 - getResources().getDimensionPixelOffset(R.dimen.dd_dimen_120px);
                                }
                                AnimationUtil.ScaleShrinkAnimator(shareLayout, ratio, -distance, new AnimatorListener() {
                                    @Override
                                    public void onAnimationEnd(Animator animation) {
                                        if (scrollLayout != null) {
                                            scrollLayout.smoothScrollTo(0, -0);
                                        }

                                    }
                                });
                            }
                        }, 150);
                        return false;
                    }
                })
                .into(shareSignImg);
    }
}
